import { Form, Input, message, Modal } from 'antd';
import moment from 'moment';
import { useMemo, useState } from 'react';

import apiConfig from '@/api/config';
import ContentList from '@/components/ContentList';
import DeleteWrapper from '@/components/DeleteWrapper';
import PageTitle from '@/components/PageTitle';
import QuickCreator from '@/components/QuickCreator';
import TButton from '@/components/TButton';
import ToolBar from '@/components/Toolbar';
import { PLAN_STAGE } from '@/const';

import PlanItem from './components/PlanItem';
import './index.less';
import { useDatabase } from '@/hooks/useDatabase';

const RESTORE_PLAN_LOCAL_KEY = 'todo-plan-restore';

export type PlanT = {
  id: string;
  name: string;
  desc: string;
  stages: PlanStageT[];
};

export type PlanStageT = {
  name: string;
  status: number; // 0代表未开始，1代表进行中，2代表已完成
  startTime: moment.Moment | '';
  finishTime: moment.Moment | '';
};

const DB_CONFIG = {
  init: true,
  getUrl: apiConfig.getPlan.url,
  restoreKey: RESTORE_PLAN_LOCAL_KEY,
  dataMapper: (i: PlanT) => {
    i.stages.forEach((s) => {
      s.startTime = s.startTime ? moment(s.startTime) : '';
      s.finishTime = s.finishTime ? moment(s.finishTime) : '';
    });
    return i;
  },
  createUrl: apiConfig.createPlan.url,
  removeUrl: apiConfig.removePlan.url,
  updateUrl: apiConfig.updatePlan.url,
};

const Plan = () => {
  const [show, setShow] = useState(false);
  const [filter, setFilter] = useState('');

  const {
    data = [],
    activeTarget,
    setActiveTarget,
    create,
    remove,
    update,
  } = useDatabase<PlanT>({
    ...DB_CONFIG,
  });

  // 右上方搜索栏根据任务名称筛选出的任务
  const filteredData = useMemo<PlanT[]>(() => {
    if (filter) {
      return data.filter((i) => i.name.includes(filter));
    } else {
      return data;
    }
  }, [data, filter]);

  const handleCreate = (v: any) => {
    const newPlan = Object.assign({}, v, {
      id: Date.now().toString(),
      stages: [],
    }) as PlanT;
    create(newPlan)
      .then(() => {
        message.success('创建计划成功！');
      })
      .catch((e) => {
        message.error('创建失败');
      });
  };

  const handleUpdate = (item: PlanT) => {
    update(item)
      .then(() => {
        message.success('已更新');
      })
      .catch((e) => {
        message.error('更新失败');
      })
      .finally(() => {
        setShow(false);
      });
  };

  const handleRemove = (item: PlanT) => {
    remove(item)
      .then(() => {
        message.success('移除成功！');
      })
      .catch((e) => {
        console.error('移除失败', e);
      });
  };

  const handleEdit = () => {
    setShow(true);
  };

  const handleCreateStage = (target: PlanT, index: number) => {
    const newStage: PlanStageT = {
      name: '任务' + Date.now().toString(),
      status: PLAN_STAGE.NO_START,
      startTime: '',
      finishTime: '',
    };
    if (index === target.stages.length) {
      target.stages.push(newStage);
    } else {
      target.stages.splice(index, 0, newStage);
      for (let i = index; i < target.stages.length; i++) {
        target.stages[i].startTime = '';
        target.stages[i].finishTime = '';
        target.stages[i].status = PLAN_STAGE.NO_START;
      }
    }
    handleUpdate(target);
  };

  const handleRemoveStage = (target: PlanT, stage: PlanStageT) => {
    const removeItem = target.stages.find((i) => i === stage);
    if (removeItem) {
      target.stages = target.stages.filter((i) => i !== stage);
    }
    handleUpdate(target);
  };

  const handleChangeStageStatus = (target: PlanT, stage: PlanStageT) => {
    const item = target.stages.find((i) => i === stage);
    if (item) {
      const convertIndexList = [
        PLAN_STAGE.NO_START,
        PLAN_STAGE.DOING,
        PLAN_STAGE.DONE,
      ];
      const currentIndex = convertIndexList.indexOf(item.status);
      item.status =
        currentIndex === 2
          ? PLAN_STAGE.NO_START
          : convertIndexList[currentIndex + 1];
      const itemIndex = target.stages.indexOf(item);
      // 当前节点未开始，则之后所有节点未开始
      if (item.status === PLAN_STAGE.NO_START) {
        for (let i = itemIndex + 1; i < target.stages.length; i++) {
          target.stages[i].status = PLAN_STAGE.NO_START;
          target.stages[i].startTime = '';
          target.stages[i].finishTime = '';
        }
        item.startTime = '';
        item.finishTime = '';
      } else if (item.status === PLAN_STAGE.DOING) {
        // 当前节点进行中，则前置节点自动完成
        for (let i = 0; i < itemIndex; i++) {
          target.stages[i].status = PLAN_STAGE.DONE;
          if (!target.stages[i].startTime) {
            target.stages[i].startTime = moment();
          }
          if (!target.stages[i].finishTime) {
            target.stages[i].finishTime = moment();
          }
        }
        item.startTime = moment();
      } else {
        item.finishTime = moment();
      }
    }
    handleUpdate(target);
  };

  const handleUpdateStage = (
    target: PlanT,
    stage: PlanStageT,
    f: string,
    v: string,
  ) => {
    const item = target.stages.find((i) => i === stage) as any;
    if (item) {
      if (f === 'time') {
        const [startTime = '', finishTime = ''] = v;
        item.startTime = startTime;
        item.finishTime = finishTime;
      } else {
        item[f] = v;
      }
    }
    handleUpdate(target);
  };

  const renderLeftActions = () => {
    return (
      <QuickCreator
        defaultFields={{
          desc: '阶段计划项目默认描述',
        }}
        mainField="name"
        onCreate={handleCreate}
        placeholder="回车快速创建阶段计划任务"
      />
    );
  };

  const renderForm = () => {
    const config = [
      {
        field: 'name',
        label: '计划名称',
        required: true,
      },
      {
        field: 'desc',
        label: '描述',
      },
      {
        field: 'id',
        label: 'id',
        hidden: true,
      },
    ];

    return (
      <Form
        name="basic"
        initialValues={activeTarget || {}}
        onFinish={handleUpdate}
        autoComplete="off"
        style={{ marginTop: '20px' }}
        layout="vertical"
      >
        {config.map((i) => (
          <Form.Item
            label={i.label}
            name={i.field}
            rules={[{ required: i.required || false }]}
            key={i.field}
            hidden={i.hidden || false}
          >
            <Input autoComplete="off" size="small" />
          </Form.Item>
        ))}
        <Form.Item>
          <TButton submit fullWidth>
            确定
          </TButton>
        </Form.Item>
      </Form>
    );
  };

  const renderListItem = (item: PlanT) => {
    return (
      <div className="plan-content-list-item">
        <DeleteWrapper
          onRemove={() => {
            handleRemove(item);
          }}
        >
          <div className="plan-content-list-item__delete">
            <span></span>
          </div>
        </DeleteWrapper>
        <span className={`plan-content-list-item__title`}>{item.name}</span>
        <span className="plan-content-list-item__desc">
          {item.stages.find((i) => i.status === PLAN_STAGE.DOING)?.name ||
            '暂无进行中'}
        </span>
      </div>
    );
  };

  const renderContent = () => {
    if (!activeTarget) {
      return <></>;
    }
    const currentStage = activeTarget.stages.find(
      (i) => i.status === PLAN_STAGE.DOING,
    );

    let index = 0;
    for (const s of activeTarget.stages) {
      if (s.status === PLAN_STAGE.DONE) {
        index++;
      } else {
        break;
      }
    }

    return (
      <>
        <PageTitle
          title={activeTarget.name}
          rightTitle={
            <div className="container">
              <TButton
                onClick={() => {
                  handleEdit();
                }}
                plain
                style={{fontSize: '12px', borderRadius: '10px'}}
              >
                编辑
              </TButton>
            </div>
          }
          subTitle={
            <div className="container">
              <div className="plan-item__info">
                <label>当前阶段</label>
                <span
                  style={{
                    color: 'var(--mainColor)',
                    marginLeft: '10px',
                    marginRight: '20px',
                  }}
                >
                  {currentStage?.name || '暂无进行中'}
                </span>
              </div>
              <div className="plan-item__progress">
                <label>进度</label>
                <span
                  style={{
                    color: 'var(--mainColor)',
                    marginLeft: '10px',
                    marginRight: '20px',
                  }}
                >{`${index} / ${activeTarget.stages.length}`}</span>
              </div>
            </div>
          }
        />
        <PlanItem
          item={activeTarget}
          key={activeTarget.id}
          onCreateStage={(index) => {
            handleCreateStage(activeTarget, index);
          }}
          onEditStage={(stage, field, v) => {
            handleUpdateStage(activeTarget, stage, field, v);
          }}
          onRemoveStage={(stage) => {
            handleRemoveStage(activeTarget, stage);
          }}
          onChangeStageStatus={(stage) => {
            handleChangeStageStatus(activeTarget, stage);
          }}
        />
      </>
    );
  };

  const renderMain = () => {
    return (
      <ContentList
        list={filteredData}
        activeKey={activeTarget?.id || ''}
        keyField="id"
        listRender={renderListItem}
        onSelect={(key) => {
          const item =
            filteredData.find((i) => i.id === key) || filteredData?.[0];
          setActiveTarget(item);
        }}
        content={renderContent()}
        tools={['search']}
        searchKey="name"
        onSearch={(v) => setFilter(v)}
      />
    );
  };

  return (
    <>
      <ToolBar leftActions={renderLeftActions()} />
      {renderMain()}
      <Modal
        visible={show}
        onCancel={() => setShow(false)}
        footer={false}
        destroyOnClose
      >
        {renderForm()}
      </Modal>
    </>
  );
};

export default Plan;
